﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraScheduler.Native;
using DevExpress.XtraScheduler;
using Gem_Tools_Utility;
using Gem_Tools_Entity.Gem_Tools;
using Gem_Tools_Controller.Gem_Tools;
using DevExpress.XtraScheduler.Drawing;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using System.Runtime.InteropServices;
using DevExpress.Utils;

namespace GE_Management_Tool.Planning.UserControl
{
    public partial class ucA0011_Tasks_Assign : DevExpress.XtraEditors.XtraUserControl
    {
        IList<CResources> m_lsResources;
        IList<CAppointments> m_lsAppointment;
        CResources m_objSelected_Res;
        CAppointments m_objSelected_Appointment;
        IList<CStaff> m_lsStaff;
        IList<CAsset> m_lsAsset;
        Boolean m_bl = false;

        //-----------------------------------
        IList<CTasks_Detail> m_lsTasks_Detail;
        IDictionary<int, int> m_dicDependencies_ID;
        IList<CTask_Dependencies> m_lsTasks_Dependencies;

        //-----------------------------------

        public ucA0011_Tasks_Assign()
        {
            InitializeComponent();

            //set trạng thái của scheduler control:
            schProject.ActiveViewType = SchedulerViewType.Gantt;
            schProject.GroupType = SchedulerGroupType.Resource;
            schProject.GanttView.CellsAutoHeightOptions.Enabled = false;
            schProject.GanttView.ResourcesPerPage = 15;
            schProject.TimelineView.ResourcesPerPage = 15;
        }

        //hàm khởi tạo toàn bộ danh sách lưới cơ bản ban đầu:
        private void Init_Scheduler_Data()
        {
            //List toàn bộ dữ liệu về Asset
            m_lsAsset = new List<CAsset>();
            CAsset_Controller v_objCtrlAsset = new CAsset_Controller();
            m_lsAsset = v_objCtrlAsset.A001_List_Asset_By_Project_ID(CConfig.g_intGem_Tools_Current_Project);
            lkeAsset.DataSource = m_lsAsset;

            //List toàn bộ dữ liệu về Staff
            m_lsStaff = new List<CStaff>();
            CStaff_Controller v_objCtrlStaff = new CStaff_Controller();
            m_lsStaff = v_objCtrlStaff.A001_sp_sel_List_Staff_By_Regency_And_Project_ID(CConfig.g_intGem_Tools_Current_Project);
            lkeStaff.DataSource = m_lsStaff;

            //Load Staff Into resrouce
            m_lsResources = new List<CResources>();
            foreach (CStaff v_staff in m_lsStaff)
            {
                CResources v_Resources = new CResources();
                v_Resources.Auto_ID = v_staff.Auto_ID;
                v_Resources.Name = v_staff.Full_Name + "(" + v_staff.UserName + ")";
                m_lsResources.Add(v_Resources);
            }

            //Load Appointment 
            m_lsAppointment = new List<CAppointments>();
            CAppointments_Controller v_CtrlAppo = new CAppointments_Controller();
            m_lsAppointment = v_CtrlAppo.A1004_sp_sel_List_Appointments_By_Project_ID(CConfig.g_intGem_Tools_Current_Project);

            cResourcesBindingSource.DataSource = m_lsResources;
            cAppointmentsBindingSource.DataSource = m_lsAppointment;
            schedulerStorage1.RefreshData();

            //------------------dependencies-------------------------------------------
            m_dicDependencies_ID = new Dictionary<int, int>();
            m_lsTasks_Dependencies = new List<CTask_Dependencies>();
        }

        int Count_Day_Of_Week(DayOfWeek pDayofWeek, DateTime pStartDate, DateTime pEndDate)
        {
            int dayCount = 0;

            for (DateTime dt = pStartDate; dt < pEndDate; dt = dt.AddDays(1.0))
            {
                if (dt.DayOfWeek == pDayofWeek)
                {
                    dayCount++;
                }
            }

            return dayCount;
        }

        private void ucA0011_Tasks_Assign_Load(object sender, EventArgs e)
        {
            try
            {
                Init_Scheduler_Data();
                schProject.OptionsCustomization.AllowAppointmentConflicts = AppointmentConflictsMode.Forbidden; 
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void schProject_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (schProject.SelectedAppointments.Count > 0)
                {
                    Appointment myAppt = schProject.SelectedAppointments[0];

                    m_objSelected_Appointment = (CAppointments)myAppt.GetRow(schedulerStorage1);

                    foreach (TreeListNode v_node in trvTasks.Nodes)
                    {
                        if (CUtility.Convert_To_Int32(v_node["AutoID"]) == CUtility.Convert_To_Int32(myAppt.ResourceId))
                        {
                            v_node.Selected = true;
                        }
                    }

                    if (myAppt.PercentComplete == 100)
                    {
                        schProject.OptionsCustomization.AllowAppointmentDrag = UsedAppointmentType.None;
                        schProject.OptionsCustomization.AllowAppointmentCreate = UsedAppointmentType.None;
                        schProject.OptionsCustomization.AllowAppointmentDelete = UsedAppointmentType.None;
                        schProject.OptionsCustomization.AllowAppointmentEdit = UsedAppointmentType.None;
                        schProject.OptionsCustomization.AllowAppointmentMultiSelect = false;
                        schProject.OptionsCustomization.AllowAppointmentResize = UsedAppointmentType.None;
                        schProject.OptionsCustomization.AllowInplaceEditor = UsedAppointmentType.None;
                        schProject.OptionsCustomization.AllowAppointmentDragBetweenResources = UsedAppointmentType.None;
                    }
                    else
                    {
                        schProject.OptionsCustomization.AllowAppointmentDrag = UsedAppointmentType.All;
                        schProject.OptionsCustomization.AllowAppointmentCreate = UsedAppointmentType.All;
                        schProject.OptionsCustomization.AllowAppointmentDelete = UsedAppointmentType.All;
                        schProject.OptionsCustomization.AllowAppointmentEdit = UsedAppointmentType.All;
                        schProject.OptionsCustomization.AllowAppointmentMultiSelect = true;
                        schProject.OptionsCustomization.AllowAppointmentResize = UsedAppointmentType.All;
                        schProject.OptionsCustomization.AllowInplaceEditor = UsedAppointmentType.All;
                        schProject.OptionsCustomization.AllowAppointmentDragBetweenResources = UsedAppointmentType.All;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void trvTasks_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            try
            {
                if (trvTasks.FocusedNode.Id >= 0)
                {
                    ResourceTreeData v_ResData = (ResourceTreeData)trvTasks.GetDataRecordByNode(trvTasks.FocusedNode);
                    m_objSelected_Res = (CResources)v_ResData.Resource.GetRow(schedulerStorage1);

                    //Init_Tasks_Detail();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void Update_Dependencies_Tasks(Appointment p_Appoint, int DaysSpan)
        {
            int value = 0;
            m_dicDependencies_ID.TryGetValue(CUtility.Convert_To_Int32(p_Appoint.ResourceId), out value);
            Appointment v_Appoint = new Appointment();
            v_Appoint = schedulerStorage1.Appointments.GetAppointmentById(value);
            if (v_Appoint != null && v_Appoint.Subject != "")
            {
                v_Appoint.Start = v_Appoint.Start.AddDays(DaysSpan);
                v_Appoint.End = v_Appoint.End.AddDays(DaysSpan);
                Update_Dependencies_Tasks(v_Appoint, DaysSpan);
            }
        }

        private void cbbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (m_bl == true)
                {
                    //Check_Date_Before_Update();
                    CTasks_Detail v_TasksDetail = new CTasks_Detail();
                    v_TasksDetail.Tasks_ID = m_objSelected_Res.Auto_ID;
                    v_TasksDetail.Date = DateTime.Now;

                    //xử lý thao tác done 1 tasks và update các task con kế tiếp của tasks đó thành dạng WIP:
                    if (cbbStatus1.SelectedIndex == CUtility.Convert_To_Int32(ETasks_Status.Done) && m_objSelected_Res.Status_ID == CUtility.Convert_To_Int32(ETasks_Status.WIP))
                    {
                        cbbStatus1.SelectedIndex = CUtility.Convert_To_Int32(ETasks_Status.Done);
                        m_objSelected_Res.Status_ID = CUtility.Convert_To_Int32(ETasks_Status.Done);
                        v_TasksDetail.Status_ID = CUtility.Convert_To_Int32(ETasks_Status.Done);
                        m_objSelected_Res.End_Date = DateTime.Now;
                    }

                    CTasks_Detail_Controller v_objCtrlTask = new CTasks_Detail_Controller();
                    v_objCtrlTask.Insert_Tasks_Detail(v_TasksDetail);

                    CResources_Controller v_objCtrlResource = new CResources_Controller();
                    v_objCtrlResource.Update_Resources(m_objSelected_Res);

                    XtraMessageBox.Show("Success !");

                    schedulerStorage1.RefreshData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void schedulerStorage1_AppointmentsChanged(object sender, PersistentObjectsEventArgs e)
        {
            try
            {
                Appointment v_Appoint = (Appointment)e.Objects[0];
                m_objSelected_Appointment = (CAppointments)v_Appoint.GetRow(schedulerStorage1);
                CAppointments_Controller v_CtrlAppo = new CAppointments_Controller();
                if (m_objSelected_Appointment.Auto_ID > 0)
                {
                    v_CtrlAppo.Update_Appointments(m_objSelected_Appointment);
                }
                schedulerStorage1.RefreshData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        //----Phần xử lý dành cho Resources------------------------------------------------------------------------------
        private void schedulerStorage1_AppointmentDependenciesInserted(object sender, PersistentObjectsEventArgs e)
        {
            try
            {
                AppointmentDependency v_appDepend = (AppointmentDependency)e.Objects[0];
                v_appDepend.Type = AppointmentDependencyType.FinishToStart;
                CTask_Dependencies v_Depen = new CTask_Dependencies();
                v_Depen.Parent_Id = CUtility.Convert_To_Int32(v_appDepend.ParentId);
                v_Depen.Dependent_ID = CUtility.Convert_To_Int32(v_appDepend.DependentId);
                v_Depen.Type = CUtility.Convert_To_Int32(v_appDepend.Type);
                CTask_Dependencies_Controller v_objCtrlDepen = new CTask_Dependencies_Controller();
                v_Depen.Auto_ID = v_objCtrlDepen.Insert_Task_Dependencies(v_Depen);
                m_lsTasks_Dependencies.Add(v_Depen);
                m_dicDependencies_ID.Add(v_Depen.Parent_Id, v_Depen.Dependent_ID);

                Appointment v_parentAppm = schedulerStorage1.Appointments.GetAppointmentById(v_appDepend.ParentId);

                //Update_Dependencies_Tasks(v_parentAppm);
                schedulerStorage1.RefreshData();
                XtraMessageBox.Show("Success !", "Warning", MessageBoxButtons.OK);

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void schedulerStorage1_AppointmentDependencyDeleting(object sender, PersistentObjectCancelEventArgs e)
        {
            try
            {
                CTask_Dependencies v_TasksDepen = (CTask_Dependencies)schProject.SelectedDependencies[0].GetRow(schedulerStorage1);
                CTask_Dependencies_Controller v_CtrlTasksDepen = new CTask_Dependencies_Controller();
                v_CtrlTasksDepen.Delete_Task_Dependencies(v_TasksDepen.Auto_ID, CSession.Active_User_Name);
                m_lsTasks_Dependencies.Remove(v_TasksDepen);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void btnAdd_task_Click(object sender, EventArgs e)
        {
            try
            {
                frmA0018_Add_Tasks v_frm = new frmA0018_Add_Tasks();
                CAppointments v_Appo = v_frm.Show_To_Display(m_objSelected_Res.Auto_ID);
                m_lsAppointment.Add(v_Appo);
                
                schedulerStorage1.RefreshData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void trvTasks_Validated(object sender, EventArgs e)
        {
            
        }

        private void trvTasks_ValidateNode(object sender, DevExpress.XtraTreeList.ValidateNodeEventArgs e)
        {
            try
            {
                CResources_Controller v_objCtrlRes = new CResources_Controller();
                v_objCtrlRes.Update_Resources(m_objSelected_Res);
                XtraMessageBox.Show("Update Success", "Warning", MessageBoxButtons.OK);

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void trvTasks_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                TreeListHitInfo ht = trvTasks.CalcHitInfo(new Point(e.X, e.Y));
                if (ht != null && ht.Node != null)
                    trvTasks.FocusedNode = ht.Node;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void toolTipController1_BeforeShow(object sender, DevExpress.Utils.ToolTipControllerShowEventArgs e)
        {
            // Get the ToolTipController.
            ToolTipController controller = sender as ToolTipController;

            AppointmentViewInfo aptViewInfo = controller.ActiveObject as AppointmentViewInfo;
            if (aptViewInfo == null) return;

            // Set a custom icon for a tooltip.
            e.IconType = ToolTipIconType.Information;

            // Set a custom title for a tooltip.
            e.Title = aptViewInfo.Appointment.Subject;

            // Set a custom text for a tooltip.
            e.ToolTip = GetCustomDescription(aptViewInfo);
        }

        string GetCustomDescription(AppointmentViewInfo aptViewInfo)
        {
            StringBuilder v_sb = new StringBuilder();
            v_sb.AppendLine(aptViewInfo.Appointment.Subject);

            return v_sb.ToString();
        }

        private void schProject_EditAppointmentFormShowing(object sender, AppointmentFormEventArgs e)
        {
            try
            {

                e.Handled = true;
                if (m_objSelected_Res == null)
                {
                    throw new Exception("- Please select 1 person to Assign. ");
                }

                frmA0018_Add_Tasks v_frm = new frmA0018_Add_Tasks();
                m_objSelected_Appointment = v_frm.Show_To_Edit(m_objSelected_Appointment);

                schedulerStorage1.RefreshData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }

        }

    }
}
